package com.sna.snaapplication.service.UserSys.impl;

import com.sna.snaapplication.entity.R;
import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.entity.usercore.core.PwdString;
import com.sna.snaapplication.entity.usercore.core.UpdateData;
import com.sna.snaapplication.mapper.UserMapper;
import com.sna.snaapplication.service.UserSys.SysUserService;
import com.sna.snaapplication.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /*
    * 根据UserId获取个人信息
    * */
    @Override
    public User findByUserName(String username) {
        User user=userMapper.findByUserName(username);
        return user;
    }

    /*
   * 更新密码
   * */
    @Override
    public R<Object> updatePwd(PwdString pwdString,String token) {
        //把原密码 转换 成加密模式 比对数据库的密码
        String oldpwd=pwdString.getOldpwd();
        String newpwd=pwdString.getNewpwd();
        String Isnewpwd=pwdString.getIsnewpwd();

        Map<String,Object> map= ThreadLocalUtil.get();
        //获取的是拦截器里面ThreadLocal得到的map类型
        String username = (String) map.get("username");
        User loginuser = userMapper.findByUserName(username);

        if(oldpwd==null||newpwd==null||Isnewpwd==null){
            return R.fail("请输入完整信息");
        }

        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();

        if(!bCryptPasswordEncoder.matches(oldpwd,loginuser.getPassword())){
            return R.fail("原密码出错");
        }
        //新密码 和确认密码 比较
        if(!newpwd.equals(Isnewpwd)){
            return R.fail("俩次密码不一致");
        }
        //加密新密码
        String updatepwd=bCryptPasswordEncoder.encode(newpwd);
        // 更新数据库中的密码
        Long userId = loginuser.getUserId();

        System.out.println("SysUserServiceImpl+userID:"+userId);
        userMapper.updatePwd(updatepwd, Math.toIntExact(userId));

        //当密码更新成功后，删除之前的token
        //需要根据键来删，因为之前用的是token也作为键，所以要知道原来的token是多少
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        //根据键来删除token
        operations.getOperations().delete(token);
        return R.ok("密码更新成功");
    }

    @Override
    public R<Object> updateUserProfile(UpdateData updateData) {
        // 更新用户信息
        Map<String,Object> map= ThreadLocalUtil.get();
        //获取的是拦截器里面ThreadLocal得到的map类型
        String username = (String) map.get("username");
        User loginuser = userMapper.findByUserName(username);
        Long userId = loginuser.getUserId();
        // 获取需要更新的字段
        String nickname = updateData.getNickName();
        String phonenumber = updateData.getPhonenumber();
        String email = updateData.getEmail();
        String sex = updateData.getSex();

        // 定义电话号码和邮箱的正则表达式
        String phoneRegex = "^1[3-9]\\d{9}$"; // 假设是验证中国大陆的手机号码
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";

        // 判空验证
        if (nickname.isEmpty() || phonenumber.isEmpty()|| email.isEmpty() || sex.isEmpty()) {
            return R.fail("修改信息不能为空");
        }
        // 验证电话号码格式
        if (phonenumber != null && !phonenumber.matches(phoneRegex)) {
            return R.fail("电话号码格式不正确");
        }

        // 验证邮箱格式
        if (email != null && !email.matches(emailRegex)) {
            return R.fail("邮箱格式不正确");
        }

        // 更新用户对象的相应字段
        loginuser.setUserId(userId);
        loginuser.setNickName(nickname);
        loginuser.setPhonenumber(phonenumber);
        loginuser.setEmail(email);
        loginuser.setSex(sex);
        //用户信息更新时间
        loginuser.setUpdateTime(new Date());



        // 执行更新操作
        int rowsAffected = userMapper.updateUser(loginuser);

        if (rowsAffected > 0) {
            // 查询更新后的用户信息
            User updatedUser = userMapper.findByUserName(loginuser.getUserName());
            return R.ok(updatedUser);
        } else {
            return R.fail("更新失败");
        }
    }

    @Override
    public User selectUserById(Long userId) {
        User user=userMapper.selectById(userId);
        return user;
    }


}
